package com.leyou.order.web;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.order.dto.OrderDTO;
import com.leyou.order.service.OrderService;
import com.leyou.order.vo.OrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 订单Controller
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 创建订单
     * @param orderDTO  接收参数: 支付类型、购物车数据、地址数据
     * @param result    接收异常信息: HibernateValidateble注解
     * @return  订单编号
     */
    @PostMapping
    public ResponseEntity<Long> createOrder(
            @RequestBody @Valid OrderDTO orderDTO, BindingResult result
    ){
        if (result.hasErrors()){
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        return ResponseEntity.status(HttpStatus.CREATED).body(orderService.createOrder(orderDTO));
    }

    /**
     * 根据id查询订单
     * @param id    订单id
     * @return      订单VO对象
     */
    @GetMapping("/{id}")
    public ResponseEntity<OrderVO> queryOrderById(
            @PathVariable("id") Long id
    ){
        OrderVO orderVO = orderService.queryOrderById(id);
        return ResponseEntity.ok(orderVO);
    }


    /**
     * 获取微信支付的二维码链接
     * @param orderId   订单编号
     * @return  微信支付链接地址
     */
    @GetMapping("/url/{id}")
    public ResponseEntity<String> getPayUrl(
            @PathVariable("id") Long orderId
    ){
        return ResponseEntity.ok(orderService.getPayUrl(orderId));
    }

    /**
     * 支付状态查询接口
     * @return
     */
    @GetMapping("/state/{id}")
    public ResponseEntity<Integer> queryPayState(
            @PathVariable("id") Long orderId
    ){
        return ResponseEntity.ok(orderService.queryPayState(orderId));
    }




    
}